package leetCode.sample;

public class LongestCommonPrefixSolution {
    public static void main(String[] args) {
        System.out.println(longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(longestCommonPrefix(new String[]{"dog", "racecar", "car"}));

        System.out.println(longestCommonPrefix2(new String[]{"flower", "flow", "flight"}));
        System.out.println(longestCommonPrefix2(new String[]{"dog", "racecar", "car"}));
    }


    public static String longestCommonPrefix2(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            while (!strs[i].startsWith(prefix)) {
                prefix = prefix.substring(0, prefix.length() - 1);
                if(prefix.isEmpty()){
                    return "";
                }
            }
        }
        return prefix;
    }

    public static String longestCommonPrefix(String[] strs) {
        int i = 0;
        if (strs.length == 0) {
            return "";
        }
        String prefix = "";
        while (i != -1) {
            char temp = '@';
            for (String str : strs) {
                if (str.length() < i + 1) {
                    i = -1;
                    break;
                }
                if (temp == '@') {
                    temp = str.charAt(i);
                    continue;
                }
                if (str.charAt(i) != temp) {
                    i = -1;
                    break;
                }
            }
            if (temp != '@' && i != -1) {
                prefix = prefix + temp;
                i++;
            }
        }
        return prefix;
    }
}
